# -*- coding: utf-8 -*-
# @Date：2024/10/4 21:13:12
# @Author：CJiaの青姝
# @FileName：check
# @Editor：PyCharm2024
# @Remark：
from typing import Any
from typing_extensions import Self

from auths.models import User
from application.models import AppDetails, AppVersion
from ninja import Router, Field, Schema, Query

from utils.cj_compare import compare_version

from utils.cj_response import SuccessResponse, ErrorResponse

router = Router()


class CheckVersionSchemaIn(Schema):
    app_id: int = Field(None, description="应用id", alias='app_id')
    version: str = Field(None, description="当前版本号", alias='version')

    def validate(cls, value: Any) -> Self:
        if value.app_id == 0 or value.app_id is None:
            return "应用id不能为空", 400
        elif value.version == '' or value.version is None:
            return "版本号不能为空", 400
        # 返回请求数据
        return value, 200

    class Config:
        title = '检查版本参数'


@router.get('/check', auth=None, summary="检查版本")
def get_app_check(request, data: CheckVersionSchemaIn = Query(...)) -> SuccessResponse | ErrorResponse:
    """ 检查版本 """
    message, code = data.validate(data)
    if code == 400:
        return ErrorResponse(msg=message)
    # 转换数据
    data = message.dict()
    # 获取应用
    app = AppDetails.objects.filter(id=data['app_id']).first()
    if not app:
        return ErrorResponse(code=400, msg="应用不存在")
    # 应用版本参数
    version_info = {
        'needUpdate': None,
        'version': None,
        'apkUrl': None,
        'wgtUrl': None,
        'HBuilderUpdate': None,
        'ForceUpdate': None,
        'description': None,
        'tip': None,
        'type': -1,
    }
    # 获取版本
    app_version = AppVersion.objects.filter(app_id=data['app_id'])
    if not app_version:
        version_info['needUpdate'] = False
        version_info['version'] = None
    if len(app_version) == 0:
        version_info['tip'] = "当前应用版本为空，请先添加应用版本"
    # 找到正式版
    for version in app_version:
        if version.formalVersion:
            version_info['needUpdate'] = True
            version_info['version'] = version.versionCode
            version_info['apkUrl'] = version.apkUrl
            version_info['wgtUrl'] = version.wgtUrl
            version_info['HBuilderUpdate'] = version.HBuilderUpdate
            version_info['ForceUpdate'] = version.ForceUpdate
            version_info['description'] = version.description
            version_info['tip'] = '当前已设置正式版'
            break
        version_info['tip'] = "当前暂未发布正式版"
    # 判断当前版本和正式版大小
    if version_info['version']:
        version_flag = compare_version(data['version'], version_info['version'])
        if version_flag == 0:
            version_info['needUpdate'] = False
            version_info['tip'] = "当前已是最新版"
            version_info['type'] = 1
        elif version_flag == -1:
            version_info['needUpdate'] = True
            version_info['tip'] = "当前低于正式版"
            version_info['type'] = 0
        elif version_flag == 1:
            version_info['needUpdate'] = False
            version_info['type'] = 2
        # 编辑对象
    result = {
        'appId': data['app_id'],
        'appName': app.appName,
        'needUpdate': version_info['needUpdate'],
        'version': version_info['version'],
        'apkUrl': version_info['apkUrl'],
        'wgtUrl': version_info['wgtUrl'],
        'HBuilderUpdate': version_info['HBuilderUpdate'],
        'ForceUpdate': version_info['ForceUpdate'],
        'description': version_info['description'],
        'tip': version_info['tip'],
        'type': version_info['type'],
    }
    # 根据应用获取用户
    user_id = AppDetails.objects.get(id=data['app_id']).user_id
    # 调用记一次记录一次
    user_info = User.objects.get(id=user_id)
    user_info.usageNumber = user_info.usageNumber + 1
    user_info.save()  # 记录+1
    # 返回结果
    return SuccessResponse(data=result)
